package com.agrimall.servlet.client;

import com.agrimall.entity.ChatMessage;
import com.agrimall.entity.ConsultationSession;
import com.agrimall.entity.User;
import com.agrimall.mapper.ChatMessageMapper;
import com.agrimall.mapper.ConsultationSessionMapper;
import com.agrimall.util.MyBatisUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户端咨询Servlet
 */
@WebServlet("/client/consultation")
public class ConsultationServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        
        if (user == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }
        
        String action = request.getParameter("action");
        
        if ("history".equals(action)) {
            // 返回历史消息（JSON格式）
            getHistoryMessages(request, response, user);
        } else if ("searchProduct".equals(action)) {
            // 根据商品名称搜索商品
            searchProduct(request, response);
        } else if ("createSession".equals(action)) {
            // 创建咨询会话
            createSession(request, response, user);
        } else {
            // 查询用户的咨询会话列表
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                ConsultationSessionMapper mapper = sqlSession.getMapper(ConsultationSessionMapper.class);
                List<ConsultationSession> sessions = mapper.selectByUserId(user.getUserId());
                request.setAttribute("sessions", sessions);
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("error", "加载咨询列表失败：" + e.getMessage());
            } finally {
                sqlSession.close();
            }
            
            request.getRequestDispatcher("/client/consultation/index.jsp").forward(request, response);
        }
    }
    
    /**
     * 获取历史消息
     */
    private void getHistoryMessages(HttpServletRequest request, HttpServletResponse response, User user)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String sessionId = request.getParameter("sessionId");
            if (sessionId == null || sessionId.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "会话ID不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                ChatMessageMapper mapper = sqlSession.getMapper(ChatMessageMapper.class);
                List<ChatMessage> messages = mapper.selectBySessionId(sessionId, 0, 1000); // 最多加载1000条
                
                // 清除用户未读消息数
                ConsultationSessionMapper sessionMapper = sqlSession.getMapper(ConsultationSessionMapper.class);
                sessionMapper.clearUnreadCount(sessionId, 0);
                sqlSession.commit();
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("messages", messages);
                out.print(objectMapper.writeValueAsString(result));
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "加载历史消息失败：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 搜索商品，返回商家列表（按商家分组）
     */
    private void searchProduct(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String productName = request.getParameter("name");
            if (productName == null || productName.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "商品名称不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            // 使用ProductService搜索商品
            com.agrimall.service.ProductService productService = new com.agrimall.service.impl.ProductServiceImpl();
            List<com.agrimall.entity.Product> products = productService.searchProducts(productName.trim(), 1, 100);
            
            // 按商家分组，每个商家只显示一次
            Map<Long, Map<String, Object>> merchantMap = new HashMap<>();
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                com.agrimall.mapper.UserMapper userMapper = sqlSession.getMapper(com.agrimall.mapper.UserMapper.class);
                
                for (com.agrimall.entity.Product product : products) {
                    Long merchantId = product.getMerchantId();
                    if (!merchantMap.containsKey(merchantId)) {
                        // 查询商家信息
                        com.agrimall.entity.User merchant = userMapper.selectById(merchantId);
                        Map<String, Object> merchantInfo = new HashMap<>();
                        merchantInfo.put("merchantId", merchantId);
                        if (merchant != null) {
                            merchantInfo.put("merchantName", merchant.getUsername() != null ? merchant.getUsername() : "未知账号");
                            merchantInfo.put("merchantRealName", merchant.getRealName() != null && !merchant.getRealName().trim().isEmpty() ? merchant.getRealName() : "未设置名称");
                        } else {
                            merchantInfo.put("merchantName", "未知账号");
                            merchantInfo.put("merchantRealName", "未设置名称");
                        }
                        merchantInfo.put("productName", product.getProductName());
                        merchantInfo.put("productId", product.getProductId());
                        merchantMap.put(merchantId, merchantInfo);
                    }
                }
            } finally {
                sqlSession.close();
            }
            
            // 转换为列表
            List<Map<String, Object>> merchantList = new java.util.ArrayList<>(merchantMap.values());
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("merchants", merchantList);
            out.print(objectMapper.writeValueAsString(result));
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "搜索商品失败：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
    
    /**
     * 创建咨询会话
     */
    private void createSession(HttpServletRequest request, HttpServletResponse response, User user)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {
            String sessionId = request.getParameter("sessionId");
            String productName = request.getParameter("productName");
            String productIdStr = request.getParameter("productId");
            
            if (sessionId == null || sessionId.trim().isEmpty()) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "会话ID不能为空");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            // 从sessionId解析信息
            String[] parts = sessionId.split("_");
            if (parts.length < 3) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "会话ID格式错误");
                out.print(objectMapper.writeValueAsString(result));
                return;
            }
            
            Long merchantId = Long.parseLong(parts[1]);
            Long productId = productIdStr != null ? Long.parseLong(productIdStr) : Long.parseLong(parts[2]);
            
            // 创建会话记录
            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            try {
                ConsultationSessionMapper mapper = sqlSession.getMapper(ConsultationSessionMapper.class);
                
                ConsultationSession session = new ConsultationSession();
                session.setSessionId(sessionId);
                session.setUserId(user.getUserId());
                session.setMerchantId(merchantId);
                session.setProductId(productId);
                session.setProductName(productName);
                session.setLastMessage(null);
                session.setLastMessageTime(new java.util.Date());
                session.setUnreadCountUser(0);
                session.setUnreadCountMerchant(0);
                
                mapper.insertOrUpdate(session);
                sqlSession.commit();
                
                Map<String, Object> result = new HashMap<>();
                result.put("success", true);
                result.put("message", "会话创建成功");
                out.print(objectMapper.writeValueAsString(result));
            } catch (Exception e) {
                sqlSession.rollback();
                e.printStackTrace();
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "创建会话失败：" + e.getMessage());
                out.print(objectMapper.writeValueAsString(result));
            } finally {
                sqlSession.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "创建会话失败：" + e.getMessage());
            out.print(objectMapper.writeValueAsString(result));
        } finally {
            out.flush();
            out.close();
        }
    }
}

